<template>
  <!-- 卡片 shadow设置阴影 -->
  <el-card shadow="hover" :body-style="{ padding: '20px' }">
    <!-- card body -->
    <!-- 按钮 -->
    <el-button type="primary" size="default" :icon="Plus" @click="addTrademark"
      >添加</el-button
    >
    <!-- 表格 border 设置表格边框-->
    <el-table
      border
      style="margin: 20px 0"
      :data="tmObj.records"
      v-loading="loading"
      element-loading-text="加载中..."
    >
      <!-- 每一列 lable 设置每列的表头 width 设置列宽  align 设置对齐方式-->
      <el-table-column
        label="序号"
        width="80"
        align="center"
        type="index"
      ></el-table-column>
      <el-table-column label="品牌名称" prop="tmName"></el-table-column>
      <el-table-column label="品牌LOGO">
        <template #="{ row, $index }">
          <a :title="row.tmName">
            <img :src="row.logoUrl" alt="" style="width: 80px; height: 60px" />
          </a>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #="{ row, $index }">
          <!-- 修改按钮 -->
          <el-button
            type="warning"
            size="small"
            :icon="Edit"
            @click="updateTrademark(row)"
          ></el-button>
          <!-- 删除按钮 -->
          <el-popconfirm
            confirm-button-text="确定"
            cancel-button-text="取消"
            :icon="Delete"
            :title="`你确定要删除${row.tmName}?`"
            @confirm="handler(row)"
          >
            <template #reference>
              <el-button type="danger" size="small" :icon="Delete"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 
    v-model:current-page
    v-model:page-size
    total
    page-sizes
    layout
    background
    pager-count
    -->
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :total="30"
      :page-sizes="[3, 5, 7]"
      layout=" prev, pager, next, jumper,->,sizes,total,"
      background
      :pager-count="7"
      @current-change="getTrademarkList"
      @size-change="sizeChange"
    >
    </el-pagination>
    <!-- 对话框 -->
    <el-dialog v-model="dialogFormVisible" :title="tmParams.id?'修改品牌':'添加品牌'">
      <el-form
        style="width: 80%"
        label-width="90px"
        :model="tmParams"
        :rules="rules"
        ref="ruleFormRef"
      >
        <!-- 获取品牌名称表单项 -->
        <el-form-item label="品牌名称" prop="tmName">
          <el-input autocomplete="off" v-model="tmParams.tmName" />
        </el-form-item>
        <!-- 获取品牌LOGO表单项 -->
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="tmParams.logoUrl"
              :src="tmParams.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="addOrUpdateTrademark"
            >确认</el-button
          >
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import type {
  trademark,
  trademarkResponseData,
} from "@/api/product/trademark/model/trademark";
import {
  reqAddOrUpdateTrademark,
  reqDeleteTrademark,
  reqTrademarkList,
} from "@/api/product/trademark/trademark";
// 引入elemen-plus中的一些图标组件
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
  Plus,
} from "@element-plus/icons-vue";
import { onMounted, reactive, ref } from "vue";
// 引入element-plus中 Upload 头像上传需要的函数(内置对象)
import { ElMessage } from "element-plus";
import type { UploadProps, FormRules, FormInstance } from "element-plus";

// 定义响应式数据
let currentPage = ref<number>(1);
let pageSize = ref<number>(3);
// 定义对话框隐藏还是展示的响应式数据
let dialogFormVisible = ref<boolean>(false);
let imageUrl = ref("");
// 定义加载状态
let loading = ref<boolean>(false);
// 获取表单DOM
let ruleFormRef = ref<FormInstance>();
// 定义服务器返回的品牌的数据
let tmObj = reactive<trademarkResponseData>({
  total: 0,
  records: [],
});

// 定义给服务器传递的参数
let tmParams = reactive<trademark>({
  tmName: "",
  logoUrl: "",
});
// 组件挂载时获取品牌数据
onMounted(() => {
  getTrademarkList();
});
// 定义获取品牌列表的方法
const getTrademarkList = async (page: number = 1) => {
  // 发前请求显示加载状态
  loading.value = true;
  // 整理数据
  currentPage.value = page;
  // 发送请求
  let result = await reqTrademarkList(currentPage.value, pageSize.value);
  console.log(result);
  tmObj.total = result.total;
  tmObj.records = result.records;
  //   服务器数据返回后隐藏加载状态
  loading.value = false;
};

// 定义切换分页器下拉选项的方法
const sizeChange = (limit: number) => {
  // 整理数据
  pageSize.value = limit;
  // 再次发送请求
  getTrademarkList();
};

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  tmParams.logoUrl = response.data;
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  // 判断图片类型
  if (
    rawFile.type == "image/jpeg" ||
    rawFile.type == "image/png" ||
    rawFile.type == "image/gif"
  ) {
    // 判断图片大小
    if (rawFile.size / 1024 / 1024 <= 5) {
      return true;
    }
  } else {
    return false;
  }
};

// 点击确定校验表单
const addOrUpdateTrademark = () => {
  ruleFormRef.value?.validate(async (success) => {
    if (success) {
      // 服务器没有返回的数据,所以不用接收了
      await reqAddOrUpdateTrademark(tmParams);
      //   关闭对话框
      dialogFormVisible.value = false;
      // 再发请求获取最新数据
      getTrademarkList(tmParams.id ? currentPage.value : 1);
      ElMessage({
        message: tmParams.id?"修改品牌成功":"添加品牌成功",
        type: "success",
      });
    } else {
      ElMessage({
        message: "品牌添加失败",
        type: "error",
      });
    }
  });
};

// 点击添加按钮清空对话框中的数据
const addTrademark = () => {
  // 显示对话框
  dialogFormVisible.value = true;
  // 清空其中的数据
  tmParams.tmName = "";
  tmParams.logoUrl = "";
  tmParams.id = "";
  ruleFormRef.value?.resetFields();
};
// 点击修改按钮弹出对话框
const updateTrademark = (row: trademark) => {
  // 显示对话框
  dialogFormVisible.value = true;
  ruleFormRef.value?.resetFields();
  tmParams.id = row.id;
  tmParams.tmName = row.tmName;
  tmParams.logoUrl = row.logoUrl;
};
// 添加表单验证规则
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: "品牌名称不能为空", trigger: "blur" },
    {
      required: true,
      min: 2,
      max: 10,
      message: "品牌名称长度为2~10之间",
      trigger: "change",
    },
  ],
  logoUrl: [{ required: true, message: "请上传品牌LOGO" }],
});

// 点击气泡框删除数据
const handler = async (row:trademark) => {
  try {
    await reqDeleteTrademark(row.id);
    ElMessage({
      message: `删除${row.tmName}成功`,
      type: "success",
    });
    getTrademarkList(currentPage.value)
  } catch (error) {
    ElMessage({
      message: `删除失败`,
      type: "error",
    });
  }
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>